import ServerUrl from "./domainConfig.js";
// import {encrypt,decrypt} from "./crypto/index.js";

let httpServer = (opts) => {
  let token = wx.getStorageSync("token");
  let promise = new Promise(function (resolve, reject) {
    const data = opts.data;
    return wx.request({
      url: ServerUrl + opts.url,
      data: data,
      header: {
        'content-type': 'application/json',
        'Authorization': token,
      },
      method: opts.method,
      success(res) {
        const data = res.data;
        if (data.code == 6010000 || data.code == 6010500) {
          wx.showModal({
            title: data.msg,
            content: data.data,
            showCancel: false,
          });
          // 非正式环境打印错误信息
          if (getApp().globalData.miniProgramInfo.envVersion !== "release") {
            console.error(data);
          }
          resolve(data);
        } else if (data.code == 10004) {
          wx.showModal({
            title: "提示",
            content: data.msg,
            showCancel: false,
          });
          resolve(data);
        } else if (data.code == 401) {
          if (wx.getStorageSync("token")) {
            wx.removeStorageSync("token");
            wx.showModal({
              title: "提示",
              content: "登录失效，请重新登录",
              showCancel: false,
              confirmText: "前往登录",
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: "/pages/login/login",
                  });
                } else if (res.cancel) {
                  console.log("用户点击取消");
                }
              },
            });
          }
          resolve(data);
        } else {
          resolve(data);
        }
      },
      fail(error) {
        wx.showModal({
          title: "提示",
          content: "网络异常",
          showCancel: false,
        });
        reject(error);
      },
    });
  });
  return promise;
};

export default httpServer;